package ui.forms;

import db.*;
import db.FoodManager;
import base.*;
import utils.DateUtils;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.animations.Transition;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.*;
import com.sun.lwuit.list.*;
import com.sun.lwuit.plaf.Border;
//import com.sun.lwuit.table.TableLayout;
import java.util.Date;

import java.util.Vector;

/**
 * Define the Layout for the form.Display the food list from local database.User
 * can select the food ,the food category and add it to the main database.
 *
 * @author Meera
 */
public class OldDiaryForm extends Form implements ActionListener {

    private static int formWidth;
    private static int formHeight;
    private Label lblQty;
    private List lstProduct;
    private List lstIn = new List();
    private Label month;
    private Label year;
    private Label day;
    private TextField dlyCal;
    private TextField txtQty;
    private Button btnAdd;
    private Button btnSave;
    private Button btnLeft;
    private Button btnDec;
    private Button btnInc;
    private Command cmdBack;
    private Container rightCon;
    private Container leftCon;
    FilterProxyListModel proxyModel;
    private static int selCount = 0;
    private Intake[] selectedItem = new Intake[100];
    private Object[] selItem = new Object[100];
    private ComboBox comboUnit;
    private String prevDay = new String();
    private String nextDay = new String();
    private static int remCal = 0;
    private float calcCal = 0;
    private User user;
    private Transition in, out;
    private ListModel FoodsModel;

    public OldDiaryForm(final Form parent) {
        cmdBack = new Command("Back") {

            public void actionPerformed(ActionEvent evt) {
                parent.showBack();
            }
        };
        addCommand(cmdBack);
        setBackCommand(cmdBack);

        setLayout(new BorderLayout());
        formWidth = getPreferredW();
        formHeight = getPreferredH();
        dlyCal = new TextField();
        dlyCal.setEditable(false);
        out = CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 500);
        in = CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 500);

        btnDec = new Button("<<");
        btnInc = new Button(">>");
        btnDec.addActionListener(this);
        btnInc.addActionListener(this);

        lstProduct = new List();
        lstProduct.setSmoothScrolling(true);
        lstProduct.getStyle().setBorder(null);
        lstProduct.setPreferredW(formWidth * 3 / 4);
        lstProduct.setPreferredH(formHeight * 6 / 9);
        lstProduct.repaint();

        lstIn = new List();
        lstIn.setSmoothScrolling(true);
        lstIn.getStyle().setBorder(null);
        lstIn.setListCellRenderer(new ui.IntakeRenderer());
        lstIn.setPreferredW(formWidth);
        lstIn.setPreferredH(formHeight / 3);

        btnInc.getSelectedStyle().setBgColor(0x336699);
        btnInc.getSelectedStyle().setFgColor(0xffffff);
        btnInc.getPressedStyle().setBgColor(0x336699);
        btnInc.getPressedStyle().setFgColor(0xffffff);
        btnInc.setFocusable(true);

        btnDec.getSelectedStyle().setBgColor(0x336699);
        btnDec.getSelectedStyle().setFgColor(0xffffff);
        btnDec.getPressedStyle().setBgColor(0x336699);
        btnDec.getPressedStyle().setFgColor(0xffffff);
        btnDec.setFocusable(true);

        String d = Integer.toString(this.getDayOfMonth());
        if (d.length() == 1) {
            d = "0" + d;
        }
        day = new Label(d);
        day.getStyle().setBgTransparency(0);
        String m = Integer.toString(this.getMonth());
        if (m.length() == 1) {
            m = "0" + m;
        }
        month = new Label(m);
        month.getStyle().setBgTransparency(0);
        int y = this.getYear();
        year = new Label("" + y);
        year.getStyle().setBgTransparency(0);

        final Container upper = new Container(new FlowLayout(Component.CENTER));

        final Container dateCnt = new Container(new BoxLayout(BoxLayout.X_AXIS));
        dateCnt.setUIID("CalendarDate");
        dateCnt.addComponent(btnDec);
        dateCnt.addComponent(day);
        dateCnt.addComponent(month);
        dateCnt.addComponent(year);
        dateCnt.addComponent(btnInc);

        upper.addComponent(dateCnt);

        final Container top = new Container(new BorderLayout());
        top.addComponent(BorderLayout.NORTH, upper);
        upper.setPreferredH(formHeight / 11);
        leftCon = this.loadLeftCon();

        Container bottomCont = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        bottomCont.addComponent(createPair("Remaining KCalories for day:", dlyCal, 6));
        user = Context.currentUser;
        remCal = (int) (user.getBMR() - this.getDlyTotCal(day.getText(), month.getText(), year.getText()));
        dlyCal.setText(Integer.toString(remCal));

        btnDec.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {

                if (evt.getSource() == btnDec) {
                    prevDay = DateUtils.DatetoString(
                            DateUtils.getYesterday(
                            DateUtils.stringToDate(day.getText() + "/" + month.getText() + "/" + year.getText())));
                    day.setText(prevDay.substring(0, 2));
                    month.setText(prevDay.substring(3, 5));
                    year.setText(prevDay.substring(6, 10));
                    day.repaint();
                    month.repaint();
                    year.repaint();

                    user = Context.currentUser;
                    remCal = (int) (user.getBMR() - getDlyTotCal(day.getText(), month.getText(), year.getText()));
                    dlyCal.setText(Integer.toString(remCal));
                    dlyCal.repaint();
                    btnDec.repaint();
                    btnDec.setFocus(true);
                }
            }
        });

        btnInc.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {

                if (evt.getSource() == btnInc) {
                    nextDay = DateUtils.DatetoString(
                            DateUtils.getNextDay(
                            DateUtils.stringToDate(day.getText() + "/" + month.getText() + "/" + year.getText())));
                    day.setText(nextDay.substring(0, 2));
                    month.setText(nextDay.substring(3, 5));
                    year.setText(nextDay.substring(6, 10));
                    day.repaint();
                    month.repaint();
                    year.repaint();

                    user = Context.currentUser;
                    remCal = (int) (user.getBMR() - getDlyTotCal(day.getText(), month.getText(), year.getText()));
                    dlyCal.setText(Integer.toString(remCal));
                    dlyCal.repaint();
                    btnInc.repaint();

                    btnInc.setFocus(true);
                }
            }
        });

        fillFoodList();
        leftCon = loadLeftCon();
        addComponent(BorderLayout.NORTH, top);
        addComponent(BorderLayout.CENTER, leftCon);
        addComponent(BorderLayout.SOUTH, bottomCont);

        addCommandListener(this);

    }

    private Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label l = new Label(label);
        Dimension dimension = l.getPreferredSize();
        dimension.setWidth(Math.max(dimension.getWidth(), minWidth));
        l.setPreferredSize(dimension);
        pair.addComponent(BorderLayout.WEST, l);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    public int getYear() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(new Date());
        return cal.get(java.util.Calendar.YEAR);
    }

    public int getDayOfMonth() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(new Date());
        return cal.get(java.util.Calendar.DAY_OF_MONTH);
    }

    public int getMonth() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(new Date());
        return (cal.get(java.util.Calendar.MONTH) + 1);
    }

    public float getDlyTotCal(String day, String month, String year) {

        float totalCal = 0;
        try {
            Vector dlyIntake = IntakeManager.getDailyIntakes(
                    Context.currentUser.getId(),
                    DateUtils.stringToDate(day + "/" + month + "/" + year));

            for (int i = 0; i < dlyIntake.size(); i++) {
                Intake intake = (Intake) dlyIntake.elementAt(i);
                totalCal += intake.getCalories();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return totalCal;
    }

    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == btnAdd) {

            if (lstProduct.getSelectedItem() == null) {
                Dialog.show("Error", "Please Select a food", "OK", "");
            } else if ((txtQty.getText().equalsIgnoreCase("")) || (comboUnit.getSelectedItem().toString() == null)) {
                Dialog.show("Error", "Please enter Quantity & Unit ", "OK", "");
            } else {

                rightCon = this.loadRightCon();

                replaceAndWait(leftCon, rightCon, out);
                dlyCal.setText(Integer.toString(remCal));
                repaint();

            }

        } else if (evt.getSource() == btnSave) {
            try {

                for (int i = 0; i < lstIn.size(); i++) {
                    ui.IntakeListItem row = (ui.IntakeListItem) lstIn.getModel().getItemAt(i);
                    selectedItem[i] = new Intake();
                    selectedItem[i].setUserId(Context.currentUser.getId());
                    Food f = FoodManager.getByName(row.getItem());
                    selectedItem[i].setFoodId(f.getId());
                    selectedItem[i].setQuantity(Float.parseFloat(row.getQty()));
                    selectedItem[i].setUnit(row.getUnit());
                    selectedItem[i].setDate(
                            DateUtils.stringToDate(day.getText() + "/" + month.getText() + "/" + year.getText()));

                    IntakeManager.persist(selectedItem[i]);
                }

                Dialog.show("Message", "Intake added successfully", "OK", "");

                for (int i = lstIn.size(); i >= 0; i--) {
                    lstIn.getModel().removeItem(i);
                }

                selCount = 0;
                lstIn.repaint();
            } catch (Exception ex) {
                ex.printStackTrace();
                Dialog.show("Error", ex.toString(), "OK", "");
            }

        } else if (evt.getSource() == btnLeft) {
            if (leftCon == null) {
                leftCon = this.loadLeftCon();
            }

            replaceAndWait(rightCon, leftCon, in);
            dlyCal.setText(Integer.toString(remCal));
            removeRightCon();

            repaint();
        }

    }

    private void fillFoodList() {

        try {
            Vector foods = FoodManager.getAll();
            String[] foodNames = new String[foods.size()];
            for (int i = 0; i < foods.size(); i++) {
                Food food = (Food) foods.elementAt(i);
                foodNames[i] = food.getName();
            }

            FoodsModel = new DefaultListModel(foodNames);
            lstProduct = new List(FoodsModel);

            lstProduct.setSmoothScrolling(true);
            lstProduct.getStyle().setBorder(null);

            lstProduct.setPreferredW(formWidth * 3 / 4);
            lstProduct.setPreferredH(formHeight * 6 / 9);
            lstProduct.repaint();


        } catch (Exception ex) {
            ex.printStackTrace();
            Dialog.show("Error", ex.toString(), "OK", "");
        }

    }

    public Container loadRightCon() {
        rightCon = new Container(new BoxLayout(BoxLayout.X_AXIS));

        try {
            float dbCal = 0;
            Label title1 = new Label("Item");
            Label title2 = new Label("Qty");
            Label title3 = new Label("Unit");
            Label title4 = new Label("KCal");
            title1.setPreferredW(60);
            title2.setPreferredW(30);
            title3.setPreferredW(40);
            title4.setPreferredW(50);
            title1.getStyle().setBorder(Border.createLineBorder(1, 0x000000));
            title2.getStyle().setBorder(Border.createLineBorder(1, 0x000000));
            title3.getStyle().setBorder(Border.createLineBorder(1, 0x000000));
            title4.getStyle().setBorder(Border.createLineBorder(1, 0x000000));
            btnSave = new Button("Save");
            btnLeft = new Button("Left");
            int index = FoodsModel.getSelectedIndex();
            dbCal = FoodManager.getByName((String) FoodsModel.getItemAt(index)).getCalories();
            calcCal = Calculator.getCalorie(txtQty.getText(), comboUnit.getSelectedItem().toString(), Float.toString(dbCal));
            remCal = (int) (remCal - calcCal);
            selItem[selCount] = new ui.IntakeListItem(
                    (String) FoodsModel.getItemAt(index),
                    txtQty.getText(),
                    comboUnit.getSelectedItem().toString(),
                    Float.toString(calcCal));
            lstIn.addItem(selItem[selCount]);
            lstIn.repaint();
            selCount++;
            final Container lstCon = new Container(new BoxLayout(BoxLayout.Y_AXIS));
            Container cnt1 = new Container(new BoxLayout(BoxLayout.X_AXIS));
            Container sveCon = new Container(new FlowLayout(Component.CENTER));
            cnt1.addComponent(title1);
            cnt1.addComponent(title2);
            cnt1.addComponent(title3);
            cnt1.addComponent(title4);
            lstCon.addComponent(cnt1);
            if (lstIn.getParent() != null) {
                lstCon.removeComponent(lstIn);
            }
            lstCon.addComponent(lstIn);
            sveCon.addComponent(btnSave);
            sveCon.addComponent(btnLeft);
            lstCon.addComponent(sveCon);
            rightCon.addComponent(lstCon);
            btnSave.addActionListener(this);
            btnLeft.addActionListener(this);
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialog.show("Error", ex.toString(), "OK", "");
        }
        return rightCon;
    }

    public Container loadLeftCon() {
        txtQty = new TextField("", 2);
        txtQty.getStyle().setBgTransparency(0);
        txtQty.setConstraint(TextArea.NUMERIC);
        txtQty.setInputMode("123");
        lblQty = new Label("Qty");
        comboUnit = new ComboBox();
        comboUnit.addItem("gm");
        comboUnit.addItem("kg");
        comboUnit.addItem("ml");
        comboUnit.addItem("ltr");
        comboUnit.getStyle().setBgTransparency(0);
        comboUnit.setEnabled(true);
        comboUnit.setFocusable(true);
        btnAdd = new Button("Add");
        btnAdd.getSelectedStyle().setBgColor(0x336699);
        btnAdd.getSelectedStyle().setFgColor(0xffffff);
        btnAdd.getPressedStyle().setBgColor(0x336699);
        btnAdd.getPressedStyle().setFgColor(0xffffff);

        leftCon = new Container(new BoxLayout(BoxLayout.X_AXIS));
        final Container leftLstCon = new Container(new BorderLayout());
        final Container leftBtCon = new Container(new BoxLayout(BoxLayout.X_AXIS));


        leftLstCon.setPreferredH(formHeight / 2);
        leftLstCon.setPreferredW(formWidth);
        leftBtCon.setPreferredH(formHeight / 12);
        leftBtCon.setPreferredW(formWidth);
        comboUnit.setPreferredW((leftLstCon.getPreferredW()) / 3);
        leftLstCon.addComponent(BorderLayout.NORTH, lstProduct);
        txtQty.setPreferredW((leftLstCon.getPreferredW()) / 3);
        leftBtCon.addComponent(lblQty);
        leftBtCon.addComponent(txtQty);
        leftBtCon.addComponent(comboUnit);
        leftBtCon.addComponent(btnAdd);
        leftLstCon.addComponent(BorderLayout.SOUTH, leftBtCon);
        leftCon.addComponent(leftLstCon);
        btnAdd.addActionListener(this);

        return leftCon;
    }

    public void removeLeftCon() {
        leftCon = null;
    }

    public void removeRightCon() {
        rightCon = null;
    }
}
